<!-- 角色编辑弹窗 -->
<template>
  <a-modal
    :width='800'
    :visible="visible"
    :confirm-loading="loading"
    :title="'授权牧场资源'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 5 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 19 }, sm: { span: 24 } }"
    >
      <a-form-item label="资源数据范围:" name="propertyScopeType">
        <a-select
          show-search
          v-model:value="form.propertyScopeType"
          placeholder="请选择资源数据范围"
          allow-clear
          @change="handleChange"
        >
          <a-select-option v-for="item in scopeData" :key="item.code">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="资源数据范围:" v-show="form.propertyScopeType !== 200">
        <a-tree
          checkable
          :checkStrictly='true'
          :load-data="loadPropertyScopeTreeData"
          :tree-data="propertyScopeTreeData"
          :fieldNames="{
            children: 'children',
            title: 'name',
            key: 'id',
            value: 'pId',
          }"
          v-model:checkedKeys="checkedKeys"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
  import { SysRoleApi } from '@/api/system/role/SysRoleApi';
  import {DeviceRecordApi} from '@/api/property/DeviceRecordApi';
  import { message } from 'ant-design-vue';
  import {eachTreeData} from "ele-admin-pro";

  export default {
    name: "RoleGrantRanchdata",
    emits: ["done", "update:visible"],
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
    },
    created() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        if (!this.form.propertyScopeType) {
          this.form = Object.assign(this.data, {"propertyScopeType" : 201});
        }
        this.isUpdate = true;
      } else {
        this.form = Object.assign({}, {"propertyScopeType" : 201});
        this.isUpdate = false;
      }
      if (this.form.propertyScopeType == 201) {
        this.queryTree();
      }
    },
    data() {
      return {
        // 表单数据
        form: Object.assign({}, this.data),
        // 表单验证规则
        rules: {
          propertyScopeType: [
            {
              required: true,
              message: "请选择资源数据范围",
              type: "number",
              trigger: "blur",
            },
          ],
        },
        scopeData: [
          { code: 201, name: "精确数据" },
          { code: 200, name: "所有数据" }
        ],
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        propertyScopeTreeData : [],
        checkedKeys : []
      };
    },

    methods: {
      // checkedNode(keys, e) {
      //   console.log(e);
      //   e.node.dataRef.selected = e.checked;
      // },
      queryTree() {
        DeviceRecordApi.propertyScopeTree({"roleId" : this.data.roleId}).then((res) => {
          // 加载框
          this.authLoading = false;
          if (res.success) {
            let treeCheckedKeys = [];
            // 组织机构数据赋值
            this.propertyScopeTreeData = res.data;
            // 遍历所有节点，所有选中的节点搜集起来
            eachTreeData(this.propertyScopeTreeData, (d) => {
              if (d.checked) {
                treeCheckedKeys.push(d.id);
              }
            });
            this.checkedKeys = treeCheckedKeys;
          } else {
            message.error(res.data.message);
          }
        })
          .catch((e) => {
            this.authLoading = false;
            message.error(e.message);
          });
      },

      loadPropertyScopeTreeData (treeNode) {
        return new Promise((resolve) => {
          if (treeNode.dataRef.children || treeNode.dataRef.isLeaf) {
            resolve();
            return;
          }
          setTimeout(() => {
            DeviceRecordApi.propertyScopeTree({"scopeTypeJoinPropertyId" : treeNode.dataRef.id, "roleId" : this.data.roleId}).then((res) => {
              // 加载框
              this.authLoading = false;
              if (res.success) {
                if (res.data && res.data.length > 0) {
                  let treeCheckedKeys = [];
                  // 组织机构数据赋值
                  treeNode.dataRef.children = res.data;
                  this.propertyScopeTreeData = [...this.propertyScopeTreeData];
                  // 遍历所有节点，所有选中的节点搜集起来
                  eachTreeData(this.propertyScopeTreeData, (d) => {
                    if (d.checked) {
                      treeCheckedKeys.push(d.id);
                    }
                  });
                  this.checkedKeys = treeCheckedKeys;
                }
              } else {
                message.error(res.data.message);
              }
              resolve();
            }).catch((e) => {
                this.authLoading = false;
                message.error(e.message);
              });
          })
        })
      },
      handleChange(value) {
        if (value == 201) {
          this.propertyScopeTreeData = [];
          this.queryTree();
        }
      },
      // 保存编辑
      async save() {
        // 校验表单
        await this.$refs.form.validate();
        // 加载中
        this.loading = true;
        let saveParams = {
          roleId: this.data.roleId,
          propertyScopeType: this.form.propertyScopeType,
        };
        if (this.form.propertyScopeType == 201) {
          saveParams.scopeTypeAndPropertyIds = this.checkedKeys?.checked;
        }

        await SysRoleApi.grantPropertyScope(saveParams)
          .then((res) => {
            // 移除加载框
            this.loading = false;
            if (res.success) {
              message.success(res.message);
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit("done");
            } else {
              message.error("操作失败：" + res.message);
            }
          })
          .catch((e) => {
            this.loading = false;
            message.error(e.message);
          });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit("update:visible", value);
      },
    },
  };
</script>

<style scoped>
</style>
